﻿using System;
using System.Linq;
using System.ServiceModel;
using BigMailer.Client.Services;

namespace BigMailer.Client
{
	public class MailerClient : IDisposable
	{
		private MailerServiceClient svc = new MailerServiceClient();
		private string authToken = null;
		private string username;
		private string password;

		public MailerClient(string username, string password, string url)
		{
			if ( !string.IsNullOrEmpty( url ) )
			{
				svc.Endpoint.Address = new EndpointAddress( url );
			}
			this.username = username;
			this.password = password;
		}

		public void Ping()
		{
			svc.Ping();
		}

		public ExistingFile[] GetPreexistingFiles()
		{
			string token = GetAuthToken();
			return svc.GetPreexistingFiles( token );
		}

		public void AbandonFile(string file)
		{
			string token = GetAuthToken();
			svc.AbandonFile( file, token );
		}

		public void BeginUpload(string FileName)
		{
			string token = GetAuthToken();
			svc.BeginUpload( FileName, token );
		}

		public void AddFilePart(string FileName, byte[] buffer)
		{
			string token = GetAuthToken();
			svc.AddFilePart( FileName, buffer, token );
		}

		public string CloseFileAndGetUrl(string file)
		{
			string token = GetAuthToken();
			return svc.CloseFileAndGetUrl( file, token );
		}

		public void MakeFileDiscoverable(string file)
		{
			string token = GetAuthToken();
			svc.MakeFileDiscoverable( file, token );
		}

		public void MakeFileUndiscoverable(string file)
		{
			string token = GetAuthToken();
			svc.MakeFileUndiscoverable( file, token );
		}

		private string GetAuthToken()
		{
			if ( authToken == null && username.Length > 0 )
			{
				authToken = svc.Authenticate( username, password );
			}
			return authToken;
		}

		public void Dispose()
		{
			svc.Close();
		}
	}
}
